package com.bluishoul.kittymeow.action;

import javax.servlet.http.HttpSession;

import com.bluishoul.kittymeow.bean.User;
import com.bluishoul.kittymeow.mvc.RequestContext;

public class UserAction {
	
	public static final String SESSION_LOGINED = "logined";
	
	RequestContext ctx;
	
	public  UserAction(RequestContext ctx){
		
		this.ctx = ctx;
		
	}
	
	public String register(){
		
		User user = ctx.form(User.class);
		
		if(user.exists()!=null)
			return "{error:'用户名已存在'}";
		
		user.setNickName(user.getUsername());
		
		long id = user.Save();
		
		ctx.request().getSession(true).setAttribute(SESSION_LOGINED, true);
		
		return "{id:'"+id+"'}";
		
	}
	
	public String login(){

		User user = ctx.form(User.class);
		
		if(user.getUsername() == null || user.getPwd()== null){
			
			return "{error:'用户名或者密码不能为空'}";
			
		}
		
		User login = user.login();
						
		if(login!=null){
			
			ctx.request().getSession(true).setAttribute(SESSION_LOGINED, true);
			
			return "{msg:'登录成功'}";
			
		}
		
		return "{error:'用户名或密码错误'}";
		
	}
	
	public String logout(){
		
		HttpSession session = ctx.request().getSession();
		
		if(session!=null)
			
			session.removeAttribute(SESSION_LOGINED);
			
		
		return "{msg:'注销成功'}";
		
	}
}
